//
//  CCQCollectionViewLeftLayout.swift
//  Fangxukanghan
//
//  Created by 常超群的MacBookPro on 2021/3/30.
//
/// 此类可以让collectionView只有一个item时候靠左
import UIKit

public class CCQCollectionViewLeftLayout: UICollectionViewFlowLayout {
    public override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        
        let attributes = super.layoutAttributesForElements(in: rect)
        if attributes?.count == 1 {
            if let currentAttribute = attributes?.first {
                
                let sectionIst = self.evaluatedSectionInsetForItem(at: currentAttribute.indexPath.section)
                currentAttribute.frame = CGRect(x: sectionIst.left, y: currentAttribute.frame.origin.y, width: currentAttribute.frame.size.width, height: currentAttribute.frame.size.height)
            }
        }
        return attributes
        
    }
    public func evaluatedSectionInsetForItem(at index: Int) ->UIEdgeInsets {
        if let delegate = self.collectionView?.delegate as? UICollectionViewDelegateFlowLayout {
            let insetForSection = delegate.collectionView?(self.collectionView!, layout: self, insetForSectionAt: index)
            if let insetForSectionAt = insetForSection {
                return insetForSectionAt
            }
        } else {
            print("请遵守代理: UICollectionViewDelegateFlowLayout, 实现方法: insetForSectionAt 或者设置 sectionInset")
        }
        return self.sectionInset
    }
}
